<template>
  <el-drawer
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :with-header="false"
    :width="700"
    :class="{'order-setting-drawer': !showMobilePage, 'mobile-drawer': showMobilePage}">
    <div v-loading="addLoading" class="order-setting-main">
      <div class="title-container">
        <Title title="自定义列" font-size="16px">
          <div class="title-tip">（勾选需要显示的列，拖动列名进行排序）</div>
        </Title>
        <el-select v-model="curView" size="small" placeholder="请选择" style="margin-right: 10px;" @change="changeView">
          <el-option
            v-for="item in viewOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id" />
        </el-select>
        <el-button v-if="curView === -1" type="info" size="small" class="default-btn" style="margin-left: 0" @click="handelView()">新建视图</el-button>
      </div>
      <div :style="{maxHeight: maxHeight}" class="draggable-container">
        <draggable
          v-model="orderList"
          v-bind="dragOptions"
          group="order"
          handle=".draggable-move"
          @change="draggablechange">
          <transition-group type="transition" class="draggable-item-list">
            <template v-for="(item) in orderList" >
              <!-- orderProps[`${settingItem.secondField || ''}.${settingItem.fieldName}`] -->
              <div v-if="getPropsData(item)" :key="item.fieldName + item.secondField || ''" :class="{'mobile-item':showMobilePage}" class="draggable-item">
                <div class="check"><el-checkbox :disabled="getPropsData(item).disableShow" v-model="item.isShow" /></div>
                <div :class="{'activetext': item.isShow}" class="draggable draggable-move one-row">
                  <ToolTip :content="getPropsData(item).label" />
                  <span v-if="getPropsData(item).disableShow" class="draggable-tag">*</span>
                </div>
                <img :src="draggableImg" class="draggable-img draggable-move" alt="" >
              </div>
            </template>
          </transition-group>
        </draggable>
        <!-- <div class="draggable-item">
          <div class="check"><el-checkbox v-model="must" disabled /></div>
          <div class="draggable">操作
            <span class="draggable-tag">*</span>
            <span class="draggable-tag">固定</span>
          </div>
        </div> -->
      </div>
    </div>
    <div class="order-setting-btn-container">
      <el-button type="primary" size="small" style="padding: 0 12px" @click="handelSubmit(false)">保存并关闭</el-button>
      <el-button v-if="curView !== -1" type="info" size="small" class="default-btn" @click="handelView(true)">保存视图</el-button>
      <el-button class="cancel-btn-style" size="small" type="info" @click="handleClose">取消</el-button>
      <img :src="resetFilterIcon" class="reset-btn" width="18" height="18" alt="" title="恢复默认" @click="handleDefault">
    </div>
    <el-dialog
      :visible.sync="creatViewVisible"
      :append-to-body="true"
      :before-close="creatViewVisibleClose"
      class="small-common-dialog-size">
      <Title title="请输入视图名称" font-size="16px" style="margin-bottom: 24px;" />
      <el-input v-model="viewName" :maxlength="50" size="small" placeholder="请输入视图名称" @keyup.enter.native="toCreateView" />
      <div class="btn-box">
        <el-button :loading="saveLoading" type="primary" size="small" @click="toCreateView">保存</el-button>
        <el-button size="small" @click="creatViewVisibleClose">取消</el-button>
      </div>
    </el-dialog>
  </el-drawer>
</template>
<script>
import Title from '@/components/Title';
import { orderProps, financeProps, initFinanceList, projectOrderProps } from './settingData';
import { legalTableProps } from '@/views/legal/tableData';
import { editOrderSetting, createOrderView, getOrderView, editOrderView } from '@/api/order';
import draggable from 'vuedraggable';
import draggableImg from '@/assets/orderlist/draggable.png';
import resetFilterIcon from '@/assets/setting/resetFilter.png';
import ElMessage from '@/utils/message';
import { mapState } from 'vuex';

export default {
  name: 'OrderSetting',
  components: { Title, draggable },
  props: {
    settingType: { // order、finance、contract、projectOrder(项目渠道单)
      type: String,
      default: 'order',
      required: true
    },
    initOrderList: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      draggableImg,
      resetFilterIcon,
      orderProps,
      financeProps, legalTableProps, projectOrderProps,
      initFinanceList,
      must: true,
      dialogVisible: false,
      addLoading: false,
      orderList: [],
      maxHeight: '',
      dragOptions: {
        animation: 200,
        group: 'description',
        disabled: false,
        ghostClass: 'ghost'
      },
      viewOptions: [{ id: -1, name: '默认视图', edit: false }],
      curView: -1,
      creatViewVisible: false,
      viewName: '',
      saveLoading: false, // 保存视图loading
      defaultSetting: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    propsData() {
      switch (this.settingType) {
        case 'order':return this.orderProps;
        case 'finance':return this.financeProps;
        case 'contract':return this.legalTableProps;
        case 'projectOrder':return this.projectOrderProps;
        default:return this.orderProps;
      }
    }
  },
  methods: {
    handelSubmit(repeat = false) {
      this.toSubmit(repeat);
    },
    async toSubmit(repeat = false) {
      let params = {};
      if (this.curView !== -1) {
        const temp = this.viewOptions.filter(item => item.id === this.curView);
        params = {
          id: this.curView,
          name: temp[0].name,
          data: JSON.stringify(this.orderList)
        };
      } else {
        params = {
          list: JSON.stringify(this.orderList),
          type: this.settingType
        };
        if (repeat) params.list = '';
      }
      const method = this.curView === -1 ? editOrderSetting : editOrderView;
      const res = await method(params);
      if (res.code === 200) {
        ElMessage.success('保存成功');
        this.$emit('handelSubmit', this.curView);
        this.handleClose();
      } else {
        ElMessage.error(res.message);
      }
    },
    getPropsData(item) {
      const propsData = this.propsData;
      if (item.secondField && item.secondField !== '') {
        return propsData[`${item.secondField}.${item.fieldName}`];
      }
      return propsData[item.fieldName];
    },
    draggablechange() {},
    openDialog(orderListSetting, curView) {
      this.getViewList();
      this.defaultSetting = orderListSetting;
      const clientHeight = window.innerHeight;
      this.maxHeight = (clientHeight - 120) + 'px';

      this.orderList = JSON.parse(JSON.stringify(orderListSetting));
      if (this.settingType === 'finance' && this.orderList) {
        const keys = this.orderList.map(i => i.fieldName);
        let newItemIndex = -1;
        const newItem = this.initFinanceList.find((i, index) => {
          if (!keys.includes(i.fieldName)) {
            newItemIndex = index;
            return true;
          }
          return false;
        });
        if (newItemIndex >= 0 && newItem) {
          newItem.isShow = false;
          this.orderList.splice(newItemIndex, 0, newItem);
        }
      }
      this.curView = curView;
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    handleDefault() {
      this.orderList = JSON.parse(JSON.stringify(this.initOrderList));
      // this.handelSubmit(true);
    },
    handelView(isSave = false) {
      if (isSave) {
        const temp = this.viewOptions.filter(item => item.id === this.curView);
        const params = {
          id: this.curView,
          name: temp[0].name,
          data: JSON.stringify(this.orderList)
        };
        editOrderView(params).then(res => {
          if (res.code === 200) {
            ElMessage.success('编辑成功');
            this.creatViewVisibleClose();
            this.getViewList();
            // 保存视图需要刷新外面视图列表的选项
            this.$emit('freshViewList');
          }
        });
      } else {
        this.creatViewVisible = true;
      }
    },
    getViewList() {
      this.addLoading = true;
      getOrderView().then((res) => {
        this.addLoading = false;
        if (res.code === 200) {
          this.viewOptions = res.data;
          this.viewOptions.unshift({ id: -1, name: '默认视图', edit: false });
        }
      }).catch(() => {
        this.addLoading = false;
      });
    },
    creatViewVisibleClose() {
      this.viewName = '';
      this.creatViewVisible = false;
    },
    toCreateView() {
      if (!this.viewName) {
        ElMessage.error('请输入视图名称');
        return;
      }
      this.saveLoading = true;
      const params = {
        name: this.viewName,
        data: JSON.stringify(this.orderList)
      };
      createOrderView(params).then(res => {
        this.saveLoading = false;
        if (res.code === 200) {
          ElMessage.success('创建成功');
          this.creatViewVisibleClose();
          this.getViewList();
          this.$emit('freshViewList');
        }
      }).catch(_ => {
        this.saveLoading = false;
      });
    },
    changeView(val) {
      const temp = this.viewOptions.filter(item => item.id === val);
      if (temp[0]) {
        if (temp[0].id === -1) {
          this.orderList = JSON.parse(JSON.stringify(this.defaultSetting));
        } else {
          this.orderList = JSON.parse(temp[0].data);
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.order-setting-drawer {
  & ::v-deep {
    .el-drawer {
      width: 695px !important;
    }
  }
  .order-setting-main {
    min-height: calc(100vh - 80px);
  }
  .default-btn {
    padding: 0;
    width: 80px;
    height: 32px;
    border: 1px solid #406eff;
    border-radius: 4px;
    font-size: 14px;
    text-align: center;
    color: #406eff;
    margin-left: 12px;
  }
}
.mobile-drawer {
    & ::v-deep {
    .el-drawer {
      width: 100% !important;
    }
  }
}
.order-setting-btn-container {
  display: flex;
  padding: 24px 24px 0 24px;
  .cancel-btn-style {
    width: 80px;
    height: 32px;
    padding: 0;
  }
  .default {
    padding: 0;
    width: 80px;
    height: 32px;
    border: 1px solid #406eff;
    border-radius: 4px;
    font-size: 14px;
    text-align: center;
    color: #406eff;
  }
  .reset-btn {
    cursor: pointer;
    margin: 7px 0 0 12px;
  }
}
.title-container {
  display: flex;
  height: 45px;
  padding: 0 24px 0 16px;
  align-items: center;
  border-bottom: 1px solid #F5F5F5;
}
.title-tip {
  font-size: 14px;
  color: #666;
}
.draggable-container {
  padding: 24px 24px 0 24px;
  @include scrollBar($x: hidden, $y: auto);
}
.draggable-item-list {
  display: flex;
  flex-wrap: wrap;
  border-top: 1px solid #EBEEFD;
  border-left: 1px solid #EBEEFD;
}
.one-row {
  display: flex;
  overflow: hidden;
  align-items: center;
}
.mobile-item {
  width: 50% !important;
}
.draggable-item {
  position: relative;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #EBEEFD;
  border-right: 1px solid #EBEEFD;
  // width: 160px;
  width: 25%;
  height: 47px;
  padding: 0 17px;
  background-color: #fff;
  overflow: hidden;
  .check {
    margin-right: 8px;
  }
  .draggable {
    flex: 1;
    font-size:14px;
    font-family:PingFangSC-Regular,PingFang SC;
    color:rgba(20,28,61,1);
    line-height:1.2;
  }
  .draggable-img {
    width: 16px;
    height: 16px;
    visibility: hidden;
    position: absolute;
    right: 6px;
    top: 15px;
  }
  &:hover {
    background-color: #FAFAFA;
    .draggable-img {
      visibility: visible;
    }
  }
  .draggable-move {
    cursor: move;
  }
  .draggable-tag {
    color: #FF4E5F;
    font-size: 12px;
    margin-left: 3px;
  }
}
.activetext{
  font-weight: bold;
}
.btn-box {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style>
